import {
  getLabelDetails
} from "../../apis/label";
import {
  globalData
} from '../../utils/request';
import cnchar from 'cnchar';
const app = getApp();

Page({
  data: {
    menuTop: null,
    menuHeight: null,
    labelInfo: {},
    rankList: [],
    indexList: []
  },

  onLoad(options) {
    let menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      menuTop: menu.top + 2,
      menuHeight: menu.height,
      showGroupBtn: globalData.checkIn
    });

    this.setData({
      labelId: options.labelId,
      labelName: options.labelName
    });
  },

  onShow() {
    this.getLabel(this.data.labelId);
  },

  getLabel(id) {
    getLabelDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;

        let indexList = [];
        data.labelCardList.forEach(v => {
          indexList.push(v.userName.substr(0, 1).spell('first'));
        });
        indexList = [...new Set(indexList.sort())];
        let rankList = indexList.map(v => {
          return {
            rank: v,
            cardList: []
          }
        });
        data.labelCardList.forEach(v => {
          rankList.forEach(val => {
            if (v.userName.substr(0, 1).spell('first') === val.rank) {
              if (v.images) {
                v.images = v.images.split(',');
                let arr = v.images.map(img => {
                  if (img.indexOf('https://') === -1 && img.indexOf('http://') === -1) img = app.globalData.url + img;
                  return img
                });
                v.images = arr;
              };
              if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
              val.cardList.push(v);
            };
          });
        });

        this.setData({
          rankList: rankList,
          labelInfo: data
        });

        let query = wx.createSelectorQuery();
        query.selectAll('.cardtitle').boundingClientRect(rect => {
          indexList = indexList.map((v, i) => {
            return {
              index: v,
              top: rect[i].top - this.data.menuTop - this.data.menuHeight
            }
          });
          this.setData({
            indexList: indexList
          });
        }).exec();
      };
    });
  },

  goIndex(e) {
    let {
      top
    } = e.currentTarget.dataset;
    wx.pageScrollTo({
      scrollTop: top,
      duration: 200,
    });
  },

  // 添加成员
  addMember() {
    wx.navigateTo({
      url: `/pages/groupEdit/index?from=label&type=add&labelId=${this.data.labelId}`,
    });
  },

  // 删除成员
  deleteMember() {
    wx.navigateTo({
      url: `/pages/groupEdit/index?from=label&type=delete&labelId=${this.data.labelId}`,
    });
  },

  goback() {
    wx.navigateBack({
      delta: 1,
    });
  }
})